package site.qianli.discover.web.resolver;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

import site.qianli.discover.common.exception.BaseException;

public class DiscoverHandlerExceptionResolver implements HandlerExceptionResolver {
	private Logger logger = LoggerFactory.getLogger(DiscoverHandlerExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ModelAndView mv = new ModelAndView();
		if (ex instanceof BaseException) {
			//系统自定义的异常
			String errorMessage = ((BaseException) ex).getErrorMessage();
			FastJsonJsonView view = new FastJsonJsonView();
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("msg", errorMessage);
			view.setAttributesMap(attributes);
			mv.setView(view);
		} else {
			//框架层面的异常
			logger.error("resolveException error", ex);
			FastJsonJsonView view = new FastJsonJsonView();
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("msg", "系统内部异常");
			view.setAttributesMap(attributes);
			mv.setView(view);
		}
		return mv;
	}
}
